package com.echo.neocommunity.controller.advice;

import com.alibaba.fastjson.JSON;
import com.echo.neocommunity.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger= LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws IOException {
        logger.error("服务器发生异常",e.getMessage());
        String xRequestedWith = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equals(xRequestedWith)){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer= response.getWriter();
            writer.write(JSON.toJSONString(R.error(-1,"服务器异常！")));
        }else{
            response.sendRedirect(request.getContextPath()+"/error");
        }
    }
}
